package edu.gzhu.guli.core.oss;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@AllArgsConstructor
public class OSSService {

  private final OSS ossClient;
  private final OSSConfiguration config;

  // 上传文件
  public String uploadFile(MultipartFile file, String storagePath) {
    String fileName = "";
    try {
      fileName = UUID.randomUUID().toString() + file.getOriginalFilename();
      InputStream inputStream = file.getInputStream();
      ObjectMetadata objectMetadata = new ObjectMetadata();
      objectMetadata.setContentLength(inputStream.available());
      objectMetadata.setCacheControl("no-cache");
      objectMetadata.setHeader("Pragma", "no-cache");
      objectMetadata.setContentType(file.getContentType());
      objectMetadata.setContentDisposition("inline;filename=" + fileName);
      fileName = storagePath + "/" + fileName;
      // 上传文件
      ossClient.putObject(config.getBucketName(), fileName, inputStream, objectMetadata);
    } catch (IOException e) {
      log.error("Error occurred: {}", e.getMessage(), e);
    }
    return fileName;
  }

  // 删除文件
  public void deleteFile(String fileName) {
    try {
      ossClient.deleteObject(config.getBucketName(), fileName);
    } catch (Exception e) {
      log.error("Error occurred: {}", e.getMessage(), e);
    }
  }

  // 下载文件
  public void exportFile(OutputStream os, String objectName) {
    OSSObject ossObject = ossClient.getObject(config.getBucketName(), objectName);
    // 读取文件内容
    BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
    BufferedOutputStream out = new BufferedOutputStream(os);
    byte[] buffer = new byte[1024];
    int lenght;
    try {
      while ((lenght = in.read(buffer)) != -1) {
        out.write(buffer, 0, lenght);
      }
      out.flush();
    } catch (IOException e) {
      log.error("Error occurred: {}", e.getMessage(), e);
    }
  }

  // 获取文件的url
  public String getSingeNatureUrl(String filename) {
    Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365);
    URL url = ossClient.generatePresignedUrl(config.getBucketName(), filename, expiration);
    if (url != null) {
      return url.toString();
    }
    return null;
  }
}
